package com.bckj.fastboot.auth.strategy;

import cn.dev33.satoken.exception.SaTokenException;
import cn.dev33.satoken.stp.StpUtil;
import com.bckj.fastboot.auth.model.LoginRequest;
import com.bckj.fastboot.auth.model.LoginResponse;
import com.bckj.fastboot.core.security.model.OauthUserDetails;
import com.bckj.fastboot.upms.api.service.SysUserRemoteService;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
public class SysAuthStrategy implements AuthStrategy {

    private static final PasswordEncoder ENCODER = new BCryptPasswordEncoder();
    private final SysUserRemoteService sysUserRemoteService;


    @Override
    @PostConstruct
    public void register() {
        AuthStrategyFactory.AUTH_STRATEGY_MAP.put(getAuthType(), this);
    }

    @Override
    public String getAuthType() {
        return "sys";
    }

    @Override
    public LoginResponse login(LoginRequest request) {
        OauthUserDetails userDetails = sysUserRemoteService.findByUsername(request.getUsername());
        if (userDetails == null) {
            throw new SaTokenException("用户不存在");
        }
        if (!ENCODER.encode(request.getPassword()).equals(userDetails.getPassword())) {
            throw new SaTokenException("账号或密码错误");
        }
        LoginResponse response = new LoginResponse();
        response.setUserId(userDetails.getId());
        StpUtil.login(userDetails.getId());
        response.setTokenInfo(StpUtil.getTokenInfo());
        return response;
    }
}
